/*  
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */


import java.awt.Container;
import java.awt.Dialog;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Scanner;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JOptionPane;

/**
 *
 * @author RaoF
 */
public class ATMFinal extends javax.swing.JFrame {
    
    // user-defined fields
    private Container main;
    private JFrame withdrawFrame;
    private JFrame currencyFrame;
    private JFrame changeFrame;
    private JFrame transferFrame;
    private Container transfer;
    private Container change;
    private Container withdraw;
    private Container currencyConverter;
    private double cash;
    private Card card;
    
    
    private static final int ID = 0, PIN = 1, BAL = 2;
    // cardCombinations[DEF_ACCNT_ID][DEF_ACCNT_PIN]
    private static Object[][] cardCombinations = {
        {"1881-A", "1234", 2000.00}, // default card 1
        {"2882-A", "8080", 1500.00}  // default card 2
    };
    
    

    /** 
     * Creates new form ATM
     */
    public ATMFinal() {
        initComponents(); // to reset the view use setContentPane
        setCard(null);
        cash = Double.MAX_VALUE;
        this.setLocationRelativeTo(null);
        updateMoney();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jPanel2 = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        jPanel3 = new javax.swing.JPanel();
        jButton1 = new javax.swing.JButton();
        jButton5 = new javax.swing.JButton();
        jButton2 = new javax.swing.JButton();
        jButton6 = new javax.swing.JButton();
        jButton3 = new javax.swing.JButton();
        jButton4 = new javax.swing.JButton();
        jPanel4 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        jLabel6 = new javax.swing.JLabel();
        jLabel5 = new javax.swing.JLabel();
        jLabel8 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);
        setResizable(false);

        jPanel1.setLayout(new java.awt.GridLayout(0, 1));

        jLabel1.setFont(new java.awt.Font("Lucida Console", 1, 18)); // NOI18N
        jLabel1.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        jLabel1.setText("Welcome");

        jLabel3.setText("Acct: ");

        javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
        jPanel2.setLayout(jPanel2Layout);
        jPanel2Layout.setHorizontalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(jLabel1, javax.swing.GroupLayout.DEFAULT_SIZE, 170, Short.MAX_VALUE)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 80, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addContainerGap())
        );
        jPanel2Layout.setVerticalGroup(
            jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel2Layout.createSequentialGroup()
                .addGap(90, 90, 90)
                .addComponent(jLabel1)
                .addGap(31, 31, 31)
                .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel3)
                    .addComponent(jLabel4, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addContainerGap(49, Short.MAX_VALUE))
        );

        jPanel1.add(jPanel2);

        jPanel3.setLayout(new java.awt.GridLayout(0, 1));

        jButton1.setText("Withdraw");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton1ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton1);

        jButton5.setText("Transfer Money");
        jButton5.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton5ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton5);

        jButton2.setText("Check Balance");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton2ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton2);

        jButton6.setText("Transaction History");
        jButton6.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton6ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton6);

        jButton3.setText("Currency Converter");
        jButton3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton3ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton3);

        jButton4.setText("Logout");
        jButton4.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButton4ActionPerformed(evt);
            }
        });
        jPanel3.add(jButton4);

        jPanel1.add(jPanel3);

        getContentPane().add(jPanel1, java.awt.BorderLayout.LINE_END);

        jPanel4.setBackground(new java.awt.Color(255, 255, 255));
        jPanel4.setMinimumSize(new java.awt.Dimension(400, 400));
        jPanel4.setPreferredSize(new java.awt.Dimension(400, 406));

        jLabel2.setText("Ads and company information here");

        jLabel6.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/metro.jpg"))); // NOI18N

        jLabel5.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/bpi.jpg"))); // NOI18N

        jLabel8.setIcon(new javax.swing.ImageIcon(getClass().getResource("/pictures/banc net.jpg"))); // NOI18N

        javax.swing.GroupLayout jPanel4Layout = new javax.swing.GroupLayout(jPanel4);
        jPanel4.setLayout(jPanel4Layout);
        jPanel4Layout.setHorizontalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel4Layout.createSequentialGroup()
                .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jLabel2))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(37, 37, 37)
                        .addGroup(jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(jLabel6)
                            .addGroup(jPanel4Layout.createSequentialGroup()
                                .addGap(10, 10, 10)
                                .addComponent(jLabel5))))
                    .addGroup(jPanel4Layout.createSequentialGroup()
                        .addGap(81, 81, 81)
                        .addComponent(jLabel8)))
                .addContainerGap(49, Short.MAX_VALUE))
        );
        jPanel4Layout.setVerticalGroup(
            jPanel4Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel4Layout.createSequentialGroup()
                .addGap(19, 19, 19)
                .addComponent(jLabel6)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 28, Short.MAX_VALUE)
                .addComponent(jLabel5)
                .addGap(26, 26, 26)
                .addComponent(jLabel8)
                .addGap(41, 41, 41)
                .addComponent(jLabel2)
                .addContainerGap())
        );

        getContentPane().add(jPanel4, java.awt.BorderLayout.CENTER);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton2ActionPerformed
        JOptionPane.showMessageDialog(this, "Account #: " + card.getAccountId()
                + "\nCurrent Balance: " + checkBalance());
    }//GEN-LAST:event_jButton2ActionPerformed
 
    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton1ActionPerformed
        this.setVisible(false);            
        withdrawFrame = new JFrame();    
        withdraw = new Withdraw(this, withdrawFrame);
        withdrawFrame.setContentPane(withdraw);
        withdrawFrame.setSize(300, 400);
        withdrawFrame.setLocationRelativeTo(this);
        withdrawFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        withdrawFrame.setVisible(true);
    }//GEN-LAST:event_jButton1ActionPerformed

    private void jButton3ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton3ActionPerformed
        this.setVisible(false);                      
        currencyFrame = new JFrame();
        currencyConverter = new Sample(this, currencyFrame);  
        currencyFrame.setContentPane(currencyConverter);
        currencyFrame.setSize(400, 400);
        currencyFrame.setLocationRelativeTo(this);
        currencyFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        currencyFrame.setVisible(true);        
    }//GEN-LAST:event_jButton3ActionPerformed

    private void jButton4ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton4ActionPerformed
        this.setVisible(false);                      
        changeFrame = new JFrame();
        change = new ChangeAccount(this, changeFrame);  
        changeFrame.setContentPane(change);
        changeFrame.setSize(300, 180);
        changeFrame.setLocationRelativeTo(this);
        changeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        changeFrame.setVisible(true);
    }//GEN-LAST:event_jButton4ActionPerformed

    private void jButton5ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton5ActionPerformed
        this.setVisible(false);            
        transferFrame = new JFrame();    
        transfer = new TransferBalance(this, transferFrame);
        transferFrame.setContentPane(transfer);
        transferFrame.setSize(400, 115);
        transferFrame.setLocationRelativeTo(this);
        transferFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        transferFrame.setVisible(true);
    }//GEN-LAST:event_jButton5ActionPerformed

    private void jButton6ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButton6ActionPerformed
        try (Scanner fileScan = new Scanner(new File("log_"+card.getAccountId()))) {
            String text = "Log :\n\n";
            while (fileScan.hasNextLine()) {
                text += fileScan.nextLine() + "\n";
            }
            
            JOptionPane.showMessageDialog(this, text);
            fileScan.close();
        } catch (IOException ioex) {
            JOptionPane.showMessageDialog(this, ioex.getMessage());
        }
        
    }//GEN-LAST:event_jButton6ActionPerformed
  
        
    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /*
         * Set the Nimbus look and feel
         */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /*
         * If Nimbus (introduced in Java SE 6) is not available, stay with the
         * default look and feel. For details see
         * http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(ATMFinal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /*
         * Create and display the form
         */
        java.awt.EventQueue.invokeLater(new Runnable() {
            
            @Override
            public void run() {
                ATMFinal atm = new ATMFinal();                     
                JFrame changeFrame = new JFrame();
                ChangeAccount change = new ChangeAccount(atm, changeFrame);  
                changeFrame.setContentPane(change);
                changeFrame.setSize(300, 180);
                changeFrame.setLocationRelativeTo(atm);
                changeFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                changeFrame.setModalExclusionType(Dialog.ModalExclusionType.APPLICATION_EXCLUDE);
                changeFrame.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JButton jButton3;
    private javax.swing.JButton jButton4;
    private javax.swing.JButton jButton5;
    private javax.swing.JButton jButton6;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JLabel jLabel5;
    private javax.swing.JLabel jLabel6;
    private javax.swing.JLabel jLabel8;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JPanel jPanel3;
    private javax.swing.JPanel jPanel4;
    // End of variables declaration//GEN-END:variables

    public void setCard(Card current) {
        if (current == null) {
            int defaultId = 0;
            card = new Card(cardCombinations[defaultId][ID].toString());
            card.setRootId(defaultId);
        } else {
            if (isValid(current)) {
                card = current;
            } else {
                // show a prompt that card is not valid
            }
        }
        
        jLabel4.setText(card.getAccountId());
    }
    
    public double checkBalance() {
        return (double) cardCombinations[card.getRootId()][BAL];
    }
    
    public boolean withdraw(String pin, double amount) {
        if (isValid(card)) {
            int rootId = card.getRootId();
            double currentBal = (double) cardCombinations[rootId][BAL];
            if (amount <= currentBal 
                    && cardCombinations[rootId][PIN].toString().equals(pin)) {
                currentBal -= amount;
                cash -= amount;
                cardCombinations[rootId][BAL] = currentBal;
                
                Scanner fileScan;                
                String text = "";
                try {
                    fileScan = new Scanner(new File("log_"+card.getAccountId()));
                    
                while (fileScan.hasNextLine()) {
                    text += fileScan.nextLine() + "\n";
                }
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(ATMFinal.class.getName()).log(Level.SEVERE, null, ex);
                }

                try (PrintWriter pw = new PrintWriter(new File("log_"+card.getAccountId()))) {
                    
                    pw.append(text + card.getAccountId()+ " withdrawn " + amount
                            + "Current BAL, " + currentBal 
                            +"\n");
                    pw.close();
                } catch (FileNotFoundException ex) {
                    JOptionPane.showMessageDialog(this, "log file not found!");
                }
                return true;
            } else {
                // cannot withdraw: not enough cash
                return false;
            }
        } else {
            // card is not valid
            return false;
        }
    }
    
    private boolean isValid(int rootId) {
        return rootId < cardCombinations.length && rootId >= 0;
    }
    
    private boolean isValid(Card current) {
        return isValid(current.getRootId())
            && cardCombinations[current.getRootId()][ID] == 
                current.getAccountId();
    }
    
    public int getRootId(String accountId) {
        for (int i = 0; i < cardCombinations.length; i++) {
            if (cardCombinations[i][ID].toString().equals(accountId)) {
                return i;
            }
        }
        return -1;
    }

    public boolean transfer(String pin, double amount, int transId) {
        if (transId == -1) {
            return(false);
        }
        if (isValid(card)) {
            int rootId = card.getRootId();
            double currentBal = (double) cardCombinations[rootId][BAL];
            if (amount <= currentBal 
                    && cardCombinations[rootId][PIN].toString().equals(pin)) {
                
                currentBal -= amount;                
                cardCombinations[rootId][BAL] = currentBal;
                
                double transBal = (double) cardCombinations[transId][BAL];
                transBal += amount;               
                cardCombinations[transId][BAL] = transBal;
                                    
                Scanner fileScan;                
                String text = "";
                
                try {
                    fileScan = new Scanner(new File("log_"+card.getAccountId()));
                    
                while (fileScan.hasNextLine()) {
                    text += fileScan.nextLine() + "\n";
                }
                } catch (FileNotFoundException ex) {
                    Logger.getLogger(ATMFinal.class.getName()).log(Level.SEVERE, null, ex);
                }
                
                try (PrintWriter pw = new PrintWriter(new File("log_"+card.getAccountId()))) {
                    pw.append(text + card.getAccountId()+ " transfered " + amount
                            + "| to " + cardCombinations[transId][ID] 
                            + "Current BAL, " + currentBal 
                            + "\n");
                    pw.close();
                } catch (FileNotFoundException ex) {
                    JOptionPane.showMessageDialog(this, "log file not found!");
                }
                return true;
            } else {
                // cannot withdraw: not enough cash
                return false;
            }
        } else {
            // card is not valid
            return false;
        }
    }

    private void updateMoney() {
        
        Scanner fileScan = null;                
        String text = "";
        try {
            fileScan = new Scanner(new File("log_"+card.getAccountId()));

        while (fileScan.hasNextLine()) {
            text += fileScan.nextLine() + "\n";
        }
        } catch (FileNotFoundException ex) {
            fileScan.close();
            return;
        }

        String[] tokens = text.split(",");
        cardCombinations[card.getRootId()][BAL] = 
                Double.parseDouble(tokens[tokens.length - 1]);
    }
}